package com.edgclub.edg;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Handler;
import android.os.Message;
import android.support.multidex.MultiDex;
import android.widget.Toast;

import com.alibaba.baichuan.android.trade.AlibcTradeSDK;
import com.alibaba.baichuan.android.trade.callback.AlibcTradeInitCallback;
import com.android.volley.RequestQueue;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.Volley;
import com.edgclub.edg.api.ApiConfig;
import com.edgclub.edg.api.CommonApi;
import com.edgclub.edg.api.FriendApi;
import com.edgclub.edg.api.UserApi;
import com.edgclub.edg.api.param.MessageParam;
import com.edgclub.edg.api.param.UserParam;
import com.edgclub.edg.event.BroadCastEvent;
import com.edgclub.edg.event.EventBus;
import com.edgclub.edg.http.VolleyListener;
import com.edgclub.edg.huanxin.DemoHelper;
import com.edgclub.edg.model.TopicChannel;
import com.edgclub.edg.model.User;
import com.edgclub.edg.model.result.RunData;
import com.edgclub.edg.model.result.UserData;
import com.edgclub.edg.model.result.WelImageData;
import com.edgclub.edg.task.UpdateManager;
import com.edgclub.edg.utils.util.BitmapUtility;
import com.edgclub.edg.utils.util.CommAppPrefUtils;
import com.edgclub.edg.utils.util.CommonUtils;
import com.edgclub.edg.utils.util.DeviceUtil;
import com.edgclub.edg.utils.util.JSONHelper;
import com.edgclub.edg.utils.util.JsonUtil;
import com.edgclub.edg.utils.util.NetworkUtility;
import com.edgclub.edg.utils.util.StringUtils;
import com.edgclub.edg.utils.util.UserPrefUtils;
import com.hyphenate.EMCallBack;
import com.hyphenate.EMGroupChangeListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.easeui.EaseConstant;
import com.hyphenate.easeui.dao.DaoHelper;
import com.hyphenate.easeui.dao.UserBeanDao;
import com.hyphenate.easeui.model.UserBean;
import com.hyphenate.easeui.model.UserChatListData;
import com.hyphenate.easeui.ui.EaseGroupRemoveListener;
import com.hyphenate.easeui.utils.EaseCommonUtils;
import com.rockerhieu.emojicon.emoji.AppInfo;
import com.rockerhieu.emojicon.emoji.CommData;
import com.rockerhieu.emojicon.emoji.CommDiledata;
import com.rockerhieu.emojicon.emoji.SerializeManager;
import com.squareup.otto.ThreadEnforcer;
import com.xiaomi.mipush.sdk.MiPushClient;
import com.youku.player.YoukuPlayerBaseConfiguration;
import com.zhzhinn.address.AddressManger;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2016/4/12.
 */
public class GuZhiApplication extends Application implements VolleyListener {
    public static Context applicationContext;
    private static GuZhiApplication instance;
    public RequestQueue mRequestQueue;


    public static GuZhiApplication getInstance() {
        return instance;
    }

    private CommonApi commonApi;

    private Handler uiHandler;

    public UserPrefUtils userPrefUtils;
    public boolean isBangdingWx;
    private static final String AUTHTAG = "QupaiAuth";
    public static String currentUserNick = "";
    public static boolean isFirstMianActivity = false;
    public boolean isFirstNew = false;
    public boolean isReportNew = false;
    public boolean isUpload;
    public static YoukuPlayerBaseConfiguration configuration;
    private ArrayList<TopicChannel> channelList;

    private AppInfo appInfo;

    @Override
    public void onCreate() {
        // begin add
        try {
            Class.forName("android.os.AsyncTask");
        } catch (Throwable ignore) {
        }
        // end add
        MultiDex.install(this);
        super.onCreate();
        mRequestQueue = Volley.newRequestQueue(getApplicationContext());
        mRequestQueue.start();
        userPrefUtils = new UserPrefUtils(this);
        applicationContext = this;
        instance = this;
        commonApi = new CommonApi(this);
        EventBus.registerApp(this);
        initUIHandler();
        loadWelImage();
        loadcommon();
        DemoHelper.getInstance().init(applicationContext);
        if (shouldInit()) {
            MiPushClient.registerPush(this, Constant.APP_ID, Constant.APP_KEY);
        }
        setMipush();

        configuration = new YoukuPlayerBaseConfiguration(this) {


            /**
             * 通过覆写该方法，返回“正在缓存视频信息的界面”，
             * 则在状态栏点击下载信息时可以自动跳转到所设定的界面.
             * 用户需要定义自己的缓存界面
             */
            @Override
            public Class<? extends Activity> getCachingActivityClass() {
                // TODO Auto-generated method stub
                return null;
            }

            /**
             * 通过覆写该方法，返回“已经缓存视频信息的界面”，
             * 则在状态栏点击下载信息时可以自动跳转到所设定的界面.
             * 用户需要定义自己的已缓存界面
             */

            @Override
            public Class<? extends Activity> getCachedActivityClass() {
                // TODO Auto-generated method stub
                return null;
            }

            /**
             * 配置视频的缓存路径，格式举例： /appname/videocache/
             * 如果返回空，则视频默认缓存路径为： /应用程序包名/videocache/
             *
             */
            @Override
            public String configDownloadPath() {
                // TODO Auto-generated method stub

                //return "/myapp/videocache/";			//举例
                return null;
            }
        };


        AlibcTradeSDK.asyncInit(this, /*Constant.TAOBAO_APPKEY,*/ new AlibcTradeInitCallback() {
            @Override
            public void onSuccess() {
                //初始化成功，设置相关的全局配置参数
//                Toast.makeText(GuZhiApplication.this, "初始化成功", Toast.LENGTH_SHORT).show();
                // ...
            }

            @Override
            public void onFailure(int code, String msg) {
                //初始化失败，可以根据code和msg判断失败原因，详情参见错误说明
//                Toast.makeText(GuZhiApplication.this, code + "初始化失败"+msg, Toast.LENGTH_SHORT).show();
            }
        });
        parseAddress();
    }

    private boolean shouldInit() {
        ActivityManager am = ((ActivityManager) getSystemService(Context.ACTIVITY_SERVICE));
        List<ActivityManager.RunningAppProcessInfo> processInfos = am.getRunningAppProcesses();
        String mainProcessName = getPackageName();
        int myPid = android.os.Process.myPid();
        for (ActivityManager.RunningAppProcessInfo info : processInfos) {
            if (info.pid == myPid && mainProcessName.equals(info.processName)) {
                return true;
            }
        }
        return false;
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

    public void setMipush() {
        MiPushClient.setAlias(applicationContext, userPrefUtils.getUser().getImid(), null);
    }

    /**
     * * 获取公共参数
     */
    public void loadcommon() {
        commonApi.getCommon(this);
    }

    /**
     * 开始加载欢迎页的图片
     */
    public void loadWelImage() {
        commonApi.welcomeImage(this);
    }

    /**
     * s刷新token接口
     */
    public void getNewToken() {
        UserParam param = new UserParam();
        param.setUsername(userPrefUtils.getName());
        param.setPwd(userPrefUtils.getPSW());
        commonApi.getToken(param, this);
    }

    public void getSysAdmin() {

        try {
            CommDiledata commDiledata = (CommDiledata) SerializeManager.loadFile(SerializeManager.regularString);
            MessageParam messageParam = new MessageParam();
            if ("".equals(GuZhiApplication.getInstance().getUserId())) {
                messageParam.setUserId("0");
            } else {
                messageParam.setUserId(GuZhiApplication.getInstance().getUserId());
            }
            String[] str = commDiledata.getSys_admin().split(",");
            boolean res = false;
            for (int i = 0; (null != str && i < str.length); i++) {
                if (!DaoHelper.getInstance(this, Constant.DB_NAME_CHAT).isHas(UserBeanDao.Properties.Imid, str[i]) && !"".equals(str[i])) {
                    res = true;
                }
            }
            if (res) {
                messageParam.setImids(commDiledata.getSys_admin());
                new FriendApi(this).getUserFromIm(messageParam, this);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取当前userid
     *
     * @return
     */
    public String getUserId() {
        return userPrefUtils.getUser().getId() + "";
    }

    public String getVersion() {
        return getVersion(getApplicationContext());
    }

    //获取版本号
    public String getVersion(Context context) {
        try {
            PackageInfo pi = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            return pi.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return "3.0";
    }

    /**
     * 获取当前登录用户的token
     *
     * @return
     */
    public String getToken() {
        return userPrefUtils.getUser().getToken();
    }

    /**
     * 获取当前登录用户的imei
     *
     * @return
     */
    public String getImei() {
        return new DeviceUtil().getIMEI(getApplicationContext());
    }

    private void initUIHandler() {
        if (uiHandler == null) {
            uiHandler = new Handler() {

                @Override
                public void handleMessage(Message msg) {
                    super.handleMessage(msg);
                }
            };
        }
    }

    public Handler getUIHandler() {
        return uiHandler;
    }

    public void setSys_admin() {
        try {
            List<UserBean> data = (List<UserBean>) SerializeManager.loadFile(EaseConstant.Sys_adminBean);
            if (null != data && data.size() > 0) {
                for (UserBean userBean : data) {
                    EMConversation conversationHistory = EMClient.getInstance().chatManager().getConversation(userBean.getImid());
                    if (null == conversationHistory || conversationHistory.getAllMsgCount() == 0) {
                        EMMessage message = EMMessage.createTxtSendMessage(" ", userBean.getImid());
                        EMClient.getInstance().chatManager().sendMessage(message);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public String getChannel() {
        String channel = CommonUtils.getMetaDataValue(applicationContext, "UMENG_CHANNEL");

        if (null == channel || "".equals(channel)) {
            channel = "guanwang";
        }
        return channel;
    }

    public void loginAgain() {

        UserParam params = new UserParam();
        params.setPwd(userPrefUtils.getPSW());
        params.setUsername(userPrefUtils.getName());
        // 开始登陆操作
        new UserApi(getApplicationContext()).login(params, this);
    }

    @Override
    public void onStart(String tag) {

    }

    @Override
    public void onSuccess(String response, String tag) {
        if (tag.equals(ApiConfig.APIURL.URL_COMMON)) {
            final CommAppPrefUtils welImagePrefUtils = new CommAppPrefUtils(
                    getApplicationContext());
            if (JSONHelper.isSuccess(response)) {
                final CommData welImageData = JsonUtil.getMode(response,
                        CommData.class);
                if (null != welImageData && null != welImageData.getData()) {
                    SerializeManager.saveFile(welImageData.getData(), SerializeManager.regularString);
                    getSysAdmin();
                }
                appInfo = welImageData.getData().getAppInfo();
                if (NetworkUtility.getNetWorkConnectionType(this) == NetworkUtility.WIFI && appInfo != null) {
                    UpdateManager updateManager = new UpdateManager(instance , appInfo);
                    updateManager.checkUpdate();
                }

            } else {
                welImagePrefUtils.clear();
            }
        } else if (tag.equals(ApiConfig.APIURL.URL_WELCOMEIMAGE)) {
            final CommAppPrefUtils commAppPrefUtils = new CommAppPrefUtils(
                    getApplicationContext());
            if (JSONHelper.isSuccess(response)) {
                final WelImageData welImageData = JsonUtil.getMode(response,
                        WelImageData.class);
                if (null != welImageData && null != welImageData.getData()
                        ) {
                    commAppPrefUtils.saveLinkUrl(welImageData.getData().getLinkUrl());

//					SerializeManager.saveFile("([http|https]+[://]+[www]?.[[A-Z,a-z,0-9,\\p{Punct},\\+]|[0-9A-Za-z:/[-]_#[?][=][.][&][%]]*]+)",SerializeManager.regularString);

                    if (null != welImageData.getData().getUrl() && !commAppPrefUtils.get().equals(
                            welImageData.getData().getUrl())) {
                        new Thread(new Runnable() {

                            @Override
                            public void run() {
                                // TODO Auto-generated method stub

                                try {
                                    File directory = new File(Constant.bgDir);
                                    if (!directory.exists()) {
                                        directory.mkdir();//没有目录先创建目录
                                    }
                                    File file = new File(Constant.bgDirImage);
                                    file.createNewFile();

                                    BitmapUtility.saveFile(BitmapUtility
                                                    .loadImageFromUrl(welImageData
                                                            .getData().getUrl()),
                                            Constant.bgDirImage);
                                    commAppPrefUtils.save(welImageData
                                            .getData().getUrl());
                                } catch (IOException e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                } catch (Exception e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                }

                            }
                        }).start();
                    }

                } else {
                    commAppPrefUtils.clear();
                }
            }
        } else if (tag.equals(ApiConfig.APIURL.URL_GETTOKEN)) {
            if (JSONHelper.isSuccess(response)) {
                RunData data = JsonUtil.getMode(response,
                        RunData.class);
                userPrefUtils.setIsLogin(true);
                userPrefUtils.savetoken(data.getData());
                Toast.makeText(applicationContext, "对不起，请重试！", Toast.LENGTH_SHORT).show();
            }
        } else if (ApiConfig.APIURL.URL_LOGIN.equals(tag)) {
            if (JSONHelper.isSuccess(response)) {
                UserData userData = JsonUtil.getMode(response, UserData.class);
                if (null != userData) {
                    User user = userData.getData();
                    if (null != user) {
                        GuZhiApplication.getInstance().setMipush();
                        // 保存密码到用户信息
                        userPrefUtils.setIsLogin(true);
                        userPrefUtils.saveUser(user);
                        if (!isUpload)
                            getSysAdmin();
                        SerializeManager.saveFile(user.getId(), Constant.currentId);
                        userPrefUtils.setDeletReply((user.getRoleCode() & PermissionsEmum.deletReply) > 0);
                        userPrefUtils.setDeletTopic((user.getRoleCode() & PermissionsEmum.deletTopic) > 0);
                        userPrefUtils.setRaiseTopic((user.getRoleCode() & PermissionsEmum.raiseTopic) > 0);
                        userPrefUtils.setMoveTopic((user.getRoleCode() & PermissionsEmum.moveTopic) > 0);
                        userPrefUtils.setReportTopic((user.getRoleCode() & PermissionsEmum.reportTopic) > 0);
                        userPrefUtils.setBanDevice((user.getRoleCode() & PermissionsEmum.banDevice) > 0);
                        userPrefUtils.setGroupAdmin((user.getRoleCode() & PermissionsEmum.groupAdmin) > 0);
                    }
                }
            } else if (JSONHelper.getResultCode(response) == 2004) {
                Toast.makeText(applicationContext,
                        StringUtils.getString(R.string.banaccount2), Toast.LENGTH_LONG)
                        .show();
                logout_edg();
            }
        } else if (tag.equals(ApiConfig.APIURL.URL_From_USER)) {
            if (JSONHelper.isSuccess(response)) {
                UserChatListData data = JsonUtil.getMode(response,
                        UserChatListData.class);
                if (null != data && null != data.getData()) {
                    isUpload = true;
                    SerializeManager.saveFile(data.getData(), Constant.Sys_adminBean);
                    for (UserBean user : data.getData()) {
                        if (!DaoHelper.getInstance(getApplicationContext(), Constant.DB_NAME_CHAT).isHas(UserBeanDao.Properties.Imid, user.getImid())) {
                            DaoHelper.getInstance(getApplicationContext(), Constant.DB_NAME_CHAT).insert(user);
                        } else {
                            DaoHelper.getInstance(getApplicationContext(), Constant.DB_NAME_CHAT).update(user);
                        }
                    }
                }
            }
        }

    }

    @Override
    public void onFaile(VolleyError volleyError, String tag) {

    }

    public void logout_edg() {
        DemoHelper.getInstance().logout(false, new EMCallBack() {

            @Override
            public void onSuccess() {
                new UserPrefUtils(applicationContext).clearUser();
                DemoHelper.getInstance().onCurrentAccountRemoved();
            }

            @Override
            public void onProgress(int progress, String status) {
            }

            @Override
            public void onError(int code, String message) {
            }
        });
    }

    public ArrayList<TopicChannel> getChannelList() {
        return channelList;
    }

    public void setChannelList(ArrayList<TopicChannel> channelList1) {
        if (channelList == null) {
            channelList = new ArrayList<>();
        }
        channelList.clear();
        for (TopicChannel channel : channelList1) {
            channelList.add(channel);
        }
    }

    public AppInfo getAppInfo() {
        return appInfo;
    }

    public void setAppInfo(AppInfo appInfo) {
        this.appInfo = appInfo;
    }

    private void parseAddress() {
        Thread thread =
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        AddressManger.getInstance().parseJson(instance);
                    }
                });
        thread.setPriority(Thread.MIN_PRIORITY);
        thread.start();
    }
}
